package com.free.semantic.core.service.impl;

import com.free.semantic.core.service.UserService;
import com.free.semantic.infrastruct.repository.UserRepository;
import com.free.semantic.model.conceptmodel.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    // 密码强度正则表达式：至少8位，包含大小写字母和数字
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$");

    @Override
    public User login(String username, String password) {
        User user = userRepository.findByUsername(username);
        if (user != null && verifyPassword(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    @Override
    public User register(String username, String password) {
        // 检查用户名是否已存在
        if (checkUsernameExists(username)) {
            return null;
        }
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(encryptPassword(password));

        Long userId = userRepository.save(user);
        user.setId(userId);
        return user;
    }

    @Override
    public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
        User user = userRepository.findById(userId);
        if (user == null || !verifyPassword(oldPassword, user.getPassword())) {
            return false;
        }

        // 检查新密码强度
        if (!validatePasswordStrength(newPassword)) {
            return false;
        }

        user.setPassword(encryptPassword(newPassword));
        userRepository.update(user);
        return true;
    }

    @Override
    public boolean checkUsernameExists(String username) {
        return userRepository.findByUsername(username) != null;
    }

    @Override
    public boolean validatePasswordStrength(String password) {
        return PASSWORD_PATTERN.matcher(password).matches();
    }

    /**
     * 加密密码
     *
     * @param password 原始密码
     * @return 加密后的密码
     */
    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    /**
     * 验证密码
     *
     * @param inputPassword     输入的密码
     * @param encryptedPassword 加密后的密码
     * @return 验证通过返回true，否则返回false
     */
    private boolean verifyPassword(String inputPassword, String encryptedPassword) {
        return encryptedPassword.equals(encryptPassword(inputPassword));
    }
} 